package com.example.chatzsyproject.fragment;

import android.animation.Animator;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.chatzsyproject.R;
import com.example.chatzsyproject.adapter.ContactsAdapter;
import com.example.chatzsyproject.base.ForResultNestedCompatFragment;
import com.example.chatzsyproject.model.FriendModel;
import com.example.chatzsyproject.ui.ApplyListActivity;
import com.example.chatzsyproject.ui.FriendMeansActivity;
import com.example.chatzsyproject.utils.AnimUtil;
import com.example.chatzsyproject.utils.PinyinUtils;
import com.example.chatzsyproject.view.AZListView.azlist.AZItemEntity;
import com.example.chatzsyproject.view.AZListView.azlist.AZTitleDecoration;
import com.example.chatzsyproject.view.AZListView.azlist.AZWaveSideBarView;
import com.example.chatzsyproject.view.AZListView.azlist.LettersComparator;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.utils.SystemConfig;
import com.hyphenate.exceptions.HyphenateException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class FragmentTwo extends ForResultNestedCompatFragment {

    @BindView(R.id.new_apply)
    TextView newApply;//有新的申请 提示
    @BindView(R.id.apply_list)
    RelativeLayout applyList;
    private View rootView;
    private Unbinder unbinder;

    @BindView(R.id.tv_title)
    TextView tv_title;

    @BindView(R.id.bar_list)
    AZWaveSideBarView mBarList;
    ContactsAdapter mAdapter;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    List<AZItemEntity<FriendModel>> dateList = new ArrayList<>();

    @BindView(R.id.im_right)
    ImageView im_right;

    private PopupWindow mPopupWindow;
    private AnimUtil animUtil;
    private static final long DURATION = 500;
    private static final float START_ALPHA = 0.7f;
    private static final float END_ALPHA = 1f;
    private float bgAlpha = 1f;
    private boolean bright = false;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what == 1){
                mAdapter.notifyDataSetChanged();
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null != rootView) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (null != parent) {
                parent.removeView(rootView);
            }
        } else {
            rootView = inflater.inflate(R.layout.fragment_two, null);
        }
        unbinder = ButterKnife.bind(this, rootView);

        if(SystemConfig.apply_list_num == 0){
            newApply.setVisibility(View.GONE);
        }else {
            newApply.setVisibility(View.VISIBLE);
            newApply.setText(SystemConfig.apply_list_num + "");
        }

        initView(rootView);// 控件初始化
        return rootView;
    }

    private void initView(View vievw) {
        mPopupWindow = new PopupWindow(getActivity());
        animUtil = new AnimUtil();

        tv_title.setText("通讯录");
        im_right.setVisibility(View.VISIBLE);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new AZTitleDecoration(new AZTitleDecoration.TitleAttributes(getActivity())));
        mAdapter = new ContactsAdapter(dateList);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListeren(new ContactsAdapter.OnItemClickListeren() {
            @Override
            public void onClick(int position) {
                Intent intent = new Intent(getActivity(), FriendMeansActivity.class);
                startActivity(intent);
            }
        });
        mBarList.setOnLetterChangeListener(new AZWaveSideBarView.OnLetterChangeListener() {
            @Override
            public void onLetterChange(String letter) {
                int position = mAdapter.getSortLettersFirstPosition(letter);
                if (position != -1) {
                    if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
                        LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                        manager.scrollToPositionWithOffset(position, 0);
                    } else {
                        recyclerView.getLayoutManager().scrollToPosition(position);
                    }
                }
            }
        });
        mAdapter.setOnItemClickListeren(new ContactsAdapter.OnItemClickListeren() {
            @Override
            public void onClick(int position) {
                startActivity(new Intent(getActivity(),FriendMeansActivity.class));
            }
        });
        im_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        getData();
    }

    private void showPop() {
        // 设置布局文件
        mPopupWindow.setContentView(LayoutInflater.from(getActivity()).inflate(R.layout.pop_conversation_add, null));
        // 为了避免部分机型不显示，我们需要重新设置一下宽高
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置pop透明效果
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(0x0000));
        // 设置pop出入动画
        mPopupWindow.setAnimationStyle(R.style.pop_add);
        // 设置pop获取焦点，如果为false点击返回按钮会退出当前Activity，如果pop中有Editor的话，focusable必须要为true
        mPopupWindow.setFocusable(true);
        // 设置pop可点击，为false点击事件无效，默认为true
        mPopupWindow.setTouchable(true);
        // 设置点击pop外侧消失，默认为false；在focusable为true时点击外侧始终消失
        mPopupWindow.setOutsideTouchable(true);
        // 相对于 + 号正下面，同时可以设置偏移量
        mPopupWindow.showAsDropDown(im_right, -100, 0);
        // 设置pop关闭监听，用于改变背景透明度
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                toggleBright();
            }
        });
    }

    private void toggleBright() {
        // 三个参数分别为：起始值 结束值 时长，那么整个动画回调过来的值就是从0.5f--1f的
        animUtil.setValueAnimator(START_ALPHA, END_ALPHA, DURATION);
        animUtil.addUpdateListener(new AnimUtil.UpdateListener() {
            @Override
            public void progress(float progress) {
                // 此处系统会根据上述三个值，计算每次回调的值是多少，我们根据这个值来改变透明度
                bgAlpha = bright ? progress : (START_ALPHA + END_ALPHA - progress);
                backgroundAlpha(bgAlpha);
            }
        });
        animUtil.addEndListner(new AnimUtil.EndListener() {
            @Override
            public void endUpdate(Animator animator) {
                // 在一次动画结束的时候，翻转状态
                bright = !bright;
            }
        });
        animUtil.startAnimator();
    }

    /**
     * 此方法用于改变背景的透明度，从而达到“变暗”的效果
     */
    private void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getActivity().getWindow().setAttributes(lp);
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    private void getData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    List<String> usernames = EMClient.getInstance().contactManager().getAllContactsFromServer();
                    List<FriendModel> itemFriend = new ArrayList<>();
                    for (String username : usernames) {
                        FriendModel friendModel = new FriendModel();
                        friendModel.setId(1);
                        friendModel.setTag("item");
                        friendModel.setHead_image("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1571215845389&di=0650e873d33f1ae914016bd41d1c3201&imgtype=0&src=http%3A%2F%2Fcdn.duitang.com%2Fuploads%2Fitem%2F201501%2F08%2F20150108164231_t432j.thumb.700_0.png");
                        friendModel.setUser_name(username);
                        itemFriend.add(friendModel);

                    }
                    dateList.addAll(fillData(itemFriend));
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                Collections.sort(dateList, new LettersComparator());
                handler.sendEmptyMessage(1);
            }
        }).start();
    }

    private List<AZItemEntity<FriendModel>> fillData(List<FriendModel> itemFriendList) {
        List<AZItemEntity<FriendModel>> sortList = new ArrayList<>();
        for (FriendModel aDate : itemFriendList) {
            AZItemEntity<FriendModel> item = new AZItemEntity<>();
            item.setValue(aDate);
            //汉字转换成拼音
            String pinyin = PinyinUtils.getPingYin(aDate);
            //取第一个首字母
            String letters = pinyin.substring(0, 1).toUpperCase();
            // 正则表达式，判断首字母是否是英文字母
            if (letters.matches("[A-Z]")) {
                item.setSortLetters(letters.toUpperCase());
            } else {
                item.setSortLetters("#");
            }
            sortList.add(item);
        }
        return sortList;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.apply_list)
    public void onViewClicked() {
        Intent intent = new Intent(getActivity(), ApplyListActivity.class);
        startActivity(intent);
    }
}
